package com.wanji.gateway.protocol;

import com.wanji.protocol.api.Protocol;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
@RequiredArgsConstructor
public class ProtocolManager {
    private final Map<String, Protocol> protocolCache = new ConcurrentHashMap<>();
    private final ProtocolLoader protocolLoader;

    public Protocol getProtocol(SocketAddress remoteAddress) {
        String clientIp = ((InetSocketAddress) remoteAddress).getAddress().getHostAddress();
        return protocolCache.computeIfAbsent(clientIp,
                protocolLoader::loadProtocolForIp);
    }

    @Scheduled(fixedRate = 60000)
    public void reloadProtocols() {
        protocolCache.replaceAll((ip, oldProtocol) ->
                protocolLoader.loadProtocolForIp(ip));
        log.info("协议配置热重载完成");
    }
}



